package com.jdbc.crud;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.jdbc.conn.Conn03;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author wzm
 * @create 2023-02-23 11:02
 */
//专门用于打开连接 和 关闭资源的工具类
public class JDBCUtils {
    //定义为全局变量
  private static DataSource dataSource = null;



    //静态代码块  类加载执行
    static {
        try {
            //加载了配置文件
            Properties properties = new Properties();
            properties.load(
                    Conn03.class
                            .getClassLoader()
                            .getResourceAsStream("druid.properties"));

            //DataSource接口有jdk指定 实现了由德鲁伊实现
             dataSource = DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConn(){
        try {
            Connection conn = dataSource.getConnection();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null;//出错返回null
    }


    //关闭资源
    public static void closes(Connection conn, PreparedStatement pst, ResultSet rs){


        try {
            if(rs != null) {
                rs.close();//关闭资源 结果集
            }

            if(pst != null) {
                pst.close();//关闭资源 执行对象
            }

            if(conn != null) {
                conn.close();//关闭资源连接
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
